/*
 * Copyright 2009 Original Author(s)
 * 
 * This file is part of Kommando
 * 
 * Kommando is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Kommando is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Kommando.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.kommando.core.command.actions.support;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * TODO write a test for this class
 * @author Peter De Bruycker
 */
public class DelayParser {
    private static Pattern PATTERN = Pattern.compile("\\s?(?:(\\d+)h)?\\s?(?:(\\d+)m)?\\s?(?:(\\d+)s)?\\s?",
            Pattern.CASE_INSENSITIVE);

    private DelayParser() {
        // static class only
    }

    public static long parse(String delayAsString) throws IllegalArgumentException {
        Matcher matcher = PATTERN.matcher(delayAsString);
        if (!matcher.matches()) {
            throw new IllegalArgumentException("invalid delay");
        }
        String hours = matcher.group(1);
        String minutes = matcher.group(2);
        String seconds = matcher.group(3);

        long delay = 0;
        if (seconds != null) {
            delay += Integer.parseInt(seconds) * 1000;
        }
        if (minutes != null) {
            delay += Integer.parseInt(minutes) * 60 * 1000;
        }
        if (hours != null) {
            delay += Integer.parseInt(hours) * 60 * 60 * 1000;
        }

        return delay;
    }
}
